import axios from "axios";
import {BASE_URL, TIMEOUT} from "./config";
import {message} from 'antd';
import errorCode from "./errorCode";
import history from "../util/history";
import {store} from "../redux/store";

const request = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT
});

// 请求拦截器
request.interceptors.request.use(config => {
  const {isToken, isFile} = config;
  if (isToken) {
    config.headers["token"] = store.getState().userInfo.token;
  }
  if (isFile) {
    config.headers["Content-Type"] = "multipart/form-data";
  } else {
    config.headers["Content-Type"] = "application/json";
  }
  return config
}, error => {
  return Promise.reject(error);
})

// 响应拦截器
request.interceptors.response.use(res => {
  const code = res.data.code || 200;
  const msg = errorCode[code] || res.data.msg || errorCode["default"];
  if (code === 401) {
    message.error("登录状态已过期，请重新登录", 3, () => {
      history.push("/login");
    })
    return Promise.reject("请重新登录");
  } else if (code === 500) {
    message.error(msg)
    return Promise.reject(new Error(msg));
  } else if (code !== 200) {
    message.error(msg);
  } else {
    message.success(msg);
    return res.data
  }
}, error => {
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        message.error("请求错误");
        break;
      case 401:
        message.error("无权限访问");
        break;
      default:
        message.error(error.response.msg + "异常");
    }
  }
  return Promise.reject(error)
})

export default request;